<?php
//This probably should return some kind of human readable error if something is wrong or missing


# TODO: Need to convert this to use PDO instead of oldish direct mysql-spesific commands
# TODO: Need a parser for different clients
# TODO: Need to detect measures or somehow bind client + units into specific measures (m/s knots/s etc)
# TODO: Re-design this shit and combine logger with xml-output and separate from the main site and
#       preferrably write a more efficient python/ruby/perl/c/java(/other?) server solution for this.

require_once("../data/common.php");

// idle before announce
$minutes = 30;

$link = mysql_connect($mysql_host, $mysql_user, $mysql_pass)
   or die('Could not connect: ' . mysql_error());
mysql_select_db($mysql_db) or die('Could not select database');

if(isset($_GET["userkey"]))	$userkey = $_GET["userkey"]; 
if(isset($_GET["username"]))	$userkey = $_GET["username"]; 
if(!isset($userkey))		$userkey = "";

if(isset($_GET["imei"])) {	$imei = $_GET["imei"]; } else { $imei = ""; } 		// => 356219xxxxxx

if(isset($_GET["lat"]))		$lat =  $_GET["lat"]; 		// => 60.239863
if(isset($_GET["latitude"]))	$lat =  $_GET["latitude"]; 		// => 60.239863
if(isset($_GET["lon"]))		$lon = $_GET["lon"]; 		// => 25.004998
if(isset($_GET["longitude"]))	$lon = $_GET["longitude"]; 		// => 25.004998
if(!isset($lat))		$lat = "";
if(!isset($lon))		$lon = "";

if(isset($_GET["status"]))	$status = $_GET["status"];	// => A
if(!isset($status))		$status = "";

if(isset($_GET["speed"]))	$speed = $_GET["speed"];	// => 1.07
if(!isset($speed))		$speed = "";

if(isset($_GET["course"]))	$course = $_GET["course"];	// => 51.85
if(isset($_GET["heading"]))	$course = $_GET["heading"];	// => 51.85
if(!isset($course))		$course = "";

if(isset($_GET["alt"]))		$alt = $_GET["alt"];		// => 65.3
if(isset($_GET["altitude"]))	$alt = $_GET["altitude"];	// => 65.3
if(!isset($alt))		$alt = "";

if(isset($_GET["time"])) 	$time = $_GET['time']; 		// => 230305.610	=> HH:MM:SS
if(isset($_GET["date"]))	$date = $_GET["date"];		// => 030307 		=> YYYY-MM-DD
if(!isset($time))		$time = "";
if(!isset($date))		$date = "";

if ($userkey == "" && $imei != "")	$userkey = $imei;


//TODO: Convert time and date to correct format and remove the following 2 lines
if (preg_match('/^([\\d]{2})([\\d]{2})([\\d]{2})/', $time, $regs)) {
	$time = $regs[1].":".$regs[2].":".$regs[3];
} else {
	$time = "";
}

if (preg_match('/^([\\d]{2})([\\d]{2})([\\d]{2,4})$/', $date, $regs)) {
	$date = $regs[1]."-".$regs[2]."-";
	if (strlen($regs[3]) == 2) {
		$date .= "20".$regs[3];
	} else {
		$date .= $regs[3];
	}
} else {
	$date = "";
}

if(isset($_GET["hdop"])) { $hdop = $_GET["hdop"]; } else { $hdop = ""; } 	// => 3.8
if(isset($_GET["cell"])) { $cell = $_GET["cell"]; } else { $cell = ""; }		// => 273619
if(isset($_GET["lac"]))  { $lac = $_GET["lac"];	} else { $lac = ""; }	// => 29111
if(isset($_GET["nwname"])) { $nwname = $_GET["nwname"]; } else { $nwname = ""; }	// => elisa
if(isset($_GET["mcc"])) { $mcc = $_GET["mcc"]; } else { $mcc = ""; }		// => 244
if(isset($_GET["mnc"]))	{	$mnc = $_GET["mnc"]; } else { $mnc = ""; }		// => 05
if(isset($_GET["ssi"]))	{	$ssi = $_GET["ssi"]; } else { $ssi = ""; }		// => 95



if ($imei == "" AND $userkey == "") {
	header($_SERVER["SERVER_PROTOCOL"]." 403 Forbidden");
	die("No identifying information");
}
$query = 'SELECT id, user_id FROM users_devices WHERE userkey = "'.mysql_real_escape_string($userkey).'"';
$result = mysql_query($query) or die( 'Problem with searching device from device_db:<br />' . mysql_error());
if (mysql_num_rows($result) != 1) {
	header($_SERVER["SERVER_PROTOCOL"]." 403 Forbidden");
	die("Oopsy daisy! Are you sure this user exists?");
} elseif (mysql_num_rows($result) > 1) {
	header($_SERVER["SERVER_PROTOCOL"]." 403 Forbidden");
	die("Something went wrong searching the device, I got too many results! Are you sending both IMEI and username/userkey?");
} else {
	$device_id = mysql_result($result, 0, "id");
	$user_id = mysql_result($result, 0, "user_id");
}

if (!empty($lat) && !empty($lon)) {
	$fields = "";
	$values = "";
	if ($status != "") { $fields .= ", status"; $values .= ', "'.mysql_real_escape_string($status).'"'; }
	if ($speed != "") { $fields .= ", speed"; $values .= ', "'.mysql_real_escape_string($speed).'"'; }
	if ($course != "") { $fields .= ", course"; $values .= ', "'.mysql_real_escape_string($course).'"'; }
	if ($date != "") { $fields .= ", gps_date"; $values .= ', "'.mysql_real_escape_string($date).'"'; }
	if ($time != "") { $fields .= ", gps_time"; $values .= ', "'.mysql_real_escape_string($time).'"'; }
	if ($alt != "") { $fields .= ", alt"; $values .= ', "'.mysql_real_escape_string($alt).'"'; }
	if ($hdop != "") { $fields .= ", hdop"; $values .= ', "'.mysql_real_escape_string($hdop).'"'; }

	$utc_time = date("Y-m-d H:i:s");
	


	$query = 'SELECT * FROM gps_current_location WHERE device_id = "'.$device_id.'"';
	$result = mysql_query($query) or die( 'Unable to get this devices current location:<br />' . mysql_error());
	$track_id = mysql_result($result, 0, "track_id");
	$time_received = mysql_result($result, 0, "time_received");
	$time_diff = time()-strtotime($time_received ? $time_received : time());

	$query = 'INSERT INTO gps_data (user_id, device_id, lat, lon '.$fields.' ,time_received ) VALUES ("'.$user_id.'", "'.$device_id.'", "'.mysql_real_escape_string($lat).'", "'.mysql_real_escape_string($lon).'" '.$values.', "'.$utc_time.'")';
	$result = mysql_query($query) or die( 'Could not insert data to archive<br /> ' . mysql_error());

	$last_row_id = mysql_insert_id();
	if ($time_diff > (60*10) ) {
		$query = 'INSERT INTO tracks (device_id,first_id,last_id,created) VALUES ('.$device_id.','.$last_row_id.','.$last_row_id.',NOW() ) ;';
		mysql_query($query) or die( 'Problem with creating new track:<br />' .  mysql_error());
		$track_id = mysql_insert_id();
	} else {
		$query = 'UPDATE tracks SET last_id = '.$last_row_id.' WHERE track_id = '.$track_id.' LIMIT 1;';
		mysql_query($query) or die( 'Problem with updating track\'s endpoint:<br />' . mysql_error());
	} 


	$query = 'SELECT * FROM gps_current_location WHERE device_id = "'.$device_id.'"';
	$result = mysql_query($query) or die( 'Unable to find out current location for this device:<br /> ' . mysql_error());
	if (mysql_num_rows($result) > 1) {
		$query = 'DELETE FROM gps_current_location WHERE device_id = "'.$device_id.'"';
		mysql_query($query) or die( 'Unable to delete current location from this device:<br />' . mysql_error());
	}
	if (mysql_num_rows($result) == 0) {
		$query = 'INSERT INTO gps_current_location (user_id, device_id, track_id, lat, lon '.$fields.' ,time_received ) VALUES ("'.$user_id.'", "'.$device_id.'", "'.$track_id.'","'.mysql_real_escape_string($lat).'", "'.mysql_real_escape_string($lon).'" '.$values.', "'.$utc_time.'")';
		mysql_query($query) or die( 'Unable to insert new line to current location table:<br /> ' . mysql_error());
	}
	if (mysql_num_rows($result) == 1) {
		$query = 'UPDATE gps_current_location SET track_id = "'.$track_id.'", time_received = "'.$utc_time.'", lat = "'.mysql_real_escape_string($lat).'", lon = "'.mysql_real_escape_string($lon).'"';
		if ($alt != "") { $query .= ', alt = "'.mysql_real_escape_string($alt).'"'; } else { $query .= ', alt = NULL'; }
		if ($status != "") { $query .= ', status = "'.mysql_real_escape_string($status).'"'; } else { $query .= ', status = NULL'; }
		if ($speed != "") { $query .= ', speed = "'.mysql_real_escape_string($speed).'"'; } else { $query .= ', speed = NULL'; }
		if ($course != "") { $query .= ', course = "'.mysql_real_escape_string($course).'"'; } else { $query .= ', course = NULL'; }
		if ($hdop != "") { $query .= ', hdop = "'.mysql_real_escape_string($hdop).'"'; } else { $query .= ', hdop = NULL'; }
		$query .= ' WHERE device_id = "'.$device_id.'"';
		mysql_query($query) or die( 'Could not update current location table:<br />' . mysql_error());
	}
}

if (!empty($cell) && !empty($lac)) {
	$fields = "";
	$values = "";
	if ($cell != "") { $fields .= ", cell"; $values .= ', "'.mysql_real_escape_string($cell).'"'; }
	if ($lac != "") { $fields .= ", lac"; $values .= ', "'.mysql_real_escape_string($lac).'"'; }
	if ($nwname != "") { $fields .= ", nwname"; $values .= ', "'.mysql_real_escape_string($nwname).'"'; }
	if ($mcc != "") { $fields .= ", mcc"; $values .= ', "'.mysql_real_escape_string($mcc).'"'; }
	if ($mnc != "") { $fields .= ", mnc"; $values .= ', "'.mysql_real_escape_string($mnc).'"'; }
	if ($ssi != "") { $fields .= ", ssi"; $values .= ', "'.mysql_real_escape_string($ssi).'"'; }
	if ($lat != "") { $fields .= ", lat"; $values .= ', "'.mysql_real_escape_string($lat).'"'; }
	if ($lon != "") { $fields .= ", lon"; $values .= ', "'.mysql_real_escape_string($lon).'"'; }

	$utc_time = date("Y-m-d H:i:s");
	
	$query = 'INSERT INTO gps_cell_data (user_id, device_id '.$fields.' ,time_received ) VALUES ("'.$user_id.'", "'.$device_id.'" '.$values.', "'.$utc_time.'")';
	echo $query;
	$result = mysql_query($query) or die( 'Could not perform SQL query: ' . mysql_error());
}

?>
